package lib;
// <editor-fold defaultstate="collapsed" desc="Imports">
import java.io.*;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
// </editor-fold> 

/**
 * @file FileHandler.java
 *
 * @version 0.1
 * @author Chris Sewell 10008342
 */
public class FileHandler {
    // <editor-fold defaultstate="collapsed" desc="Attributes">

    URL fileDir;
    File file;
    FileInputStream fileInStream;
    FileOutputStream fileOutStream;
    int length;
    // </editor-fold> 
    // <editor-fold defaultstate="collapsed" desc="Constructors">

    /**
     * File constructor for reading from files 
     * Constructor uses FileInputStream
     */
    public FileHandler(String fileName) throws FileNotFoundException {
        //This will fail in windows XP UWE
        file = new File(fileName);
        if (file.exists()) {
            length = (int) file.length();
            fileInStream = new FileInputStream(file);
        }
    }

    /**
     * File constructor for writing to files 
     * Constructor uses FileOutputStream
     */
    public FileHandler(String fileName, int length) {
        //This will fail in windows XP UWE
        fileName = fileName.replaceAll("my", "new");
        file = new File(fileName);
        this.length = length;
        try {
            file.createNewFile();
            fileOutStream = new FileOutputStream(file);
        } catch (IOException ex) {
            Logger.getLogger(FileHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    // </editor-fold> 
    // <editor-fold defaultstate="collapsed" desc="Methods">

    /**
     * These abstractions hide the try catch statements and closure required for reading/writing to files
     */
    public void writeToFIle(byte[] data) {//Write a byte array to file then close
        try {
            fileOutStream.write(data, 0, length);
            fileOutStream.close();
        } catch (IOException ex) {
            Logger.getLogger(FileHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public byte[] readFromFile() {//Read a byte array from file then close
        byte[] data = new byte[length];
        try {
            fileInStream.read(data, 0, length);
            fileInStream.close();
        } catch (IOException ex) {
            Logger.getLogger(FileHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
        return data;
    }
    //Methods I have used for debugging when handling files

    public String getFileDir() {
        return fileDir.getPath();
    }

    public String getFileName() {
        return file.getName();
    }
    // </editor-fold> 
}
